//
//  MJ_CalendarView.m
//  UEAssistant
//
//  Created by mac on 2018/1/8.
//  Copyright © 2018年 youyixinxi. All rights reserved.
//

#import "MJ_CalendarView.h"
#import "UIColor+Extend.h"
#import <FSCalendar.h>
#import "RangePickerCell.h"

@interface MJ_CalendarView ()<FSCalendarDataSource,FSCalendarDelegate,FSCalendarDelegateAppearance>

@property (strong, nonatomic)UIWindow *backgroundWindow;

@property (strong, nonatomic) FSCalendar *calendar;

@property (weak, nonatomic) UILabel *eventLabel;

@property (strong, nonatomic) NSCalendar *gregorian;

@property (strong, nonatomic) NSDateFormatter *dateFormatter;

// The start date of the range
@property (strong, nonatomic) NSDate *startDate;
// The end date of the range
@property (strong, nonatomic) NSDate *endDate;

@property (strong, nonatomic)UILabel *startTitleLabel;
@property (strong, nonatomic)UILabel *endTitleLabel;
@property (strong, nonatomic)UILabel *startDateLabel;
@property (strong, nonatomic)UILabel *endDateLabel;
@property (strong, nonatomic)UIView *blueLine;
@end

@implementation MJ_CalendarView

#pragma mark --- 初始化
- (UIWindow *)backgroundWindow {
    if (!_backgroundWindow) {
        _backgroundWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _backgroundWindow.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.8];
    }
    return _backgroundWindow;
}

- (UILabel *)startDateLabel {
    if (!_startDateLabel) {
        _startDateLabel = [[UILabel alloc] init];
        _startDateLabel.frame = CGRectMake(0, 45+22, Screen_Width/2.0, 22);
        _startDateLabel.font = [UIFont systemFontOfSize:12];
        _startDateLabel.textColor = [UIColor colorWithHexString:@"#666666"];
        _startDateLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _startDateLabel;
}

- (UILabel *)endDateLabel {
    if (!_endDateLabel) {
        _endDateLabel = [[UILabel alloc] init];
        _endDateLabel.frame = CGRectMake(Screen_Width/2.0, 45+22, Screen_Width/2.0, 22);
        _endDateLabel.font = [UIFont systemFontOfSize:12];
        _endDateLabel.textColor = [UIColor colorWithHexString:@"#666666"];
        _endDateLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _endDateLabel;
}


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.layer.cornerRadius = 10.0;
        self.layer.masksToBounds = YES;
        self.backgroundColor = [UIColor whiteColor];
        [self setupUI];
    }
    return self;
}
//初始化固定组件
- (void)setupUI {
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, 44)];
    title.text = @"选择日期";
    title.font = [UIFont systemFontOfSize:17];
    title.textColor = [UIColor colorWithHexString:@"#383838"];
    title.textAlignment = NSTextAlignmentCenter;
    title.backgroundColor = [UIColor whiteColor];
    [self addSubview:title];
    
    UIButton *cancel = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancel setTitle:@"取消" forState:UIControlStateNormal];
    cancel.titleLabel.font = [UIFont systemFontOfSize:15];
    [cancel setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:UIControlStateNormal];
    cancel.frame = CGRectMake(15, 0, 40, 44);
    [cancel addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:cancel];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 44, Screen_Width, 1)];
    line.backgroundColor = [UIColor colorWithHexString:@"#eeeeee"];
    [self addSubview:line];
    
    UILabel *startTimeTitle = [[UILabel alloc] init];
    startTimeTitle.text = @"开始日期";
    startTimeTitle.textColor = mainColor;
    startTimeTitle.frame = CGRectMake(0, 45, Screen_Width/2.0, 44);
    startTimeTitle.textAlignment = NSTextAlignmentCenter;
    startTimeTitle.backgroundColor = [UIColor whiteColor];
    startTimeTitle.font = [UIFont systemFontOfSize:15];
    [self addSubview:startTimeTitle];
    self.startTitleLabel = startTimeTitle;
    
    UILabel *endTimeTitle = [[UILabel alloc] init];
    endTimeTitle.text = @"结束日期";
    endTimeTitle.backgroundColor = [UIColor whiteColor];
    endTimeTitle.textColor = mainColor;
    endTimeTitle.frame = CGRectMake(Screen_Width/2.0, 45, Screen_Width/2.0, 44);
    endTimeTitle.textAlignment = NSTextAlignmentCenter;
    endTimeTitle.font = [UIFont systemFontOfSize:15];
    [self addSubview:endTimeTitle];
    self.endTitleLabel = endTimeTitle;
    
    _blueLine = [[UIView alloc] init];
    _blueLine.backgroundColor = mainColor;
    if (_isStartDate) {
        _blueLine.frame = CGRectMake(0, 86, Screen_Width/2.0, 4);
    }else{
        _blueLine.frame = CGRectMake(Screen_Width/2.0, 86, Screen_Width/2.0, 4);
    }
    [self addSubview:_blueLine];
    
    NSArray *weekArray = @[@"日",@"一",@"二",@"三",@"四",@"五",@"六"];
    for (NSInteger i = 0; i < 7; ++ i) {
        UILabel *week = [[UILabel alloc] initWithFrame:CGRectMake(Screen_Width/7.0*i, 90, Screen_Width/7.0, 25)];
        if (i == 0 || i == 6) {
            week.textColor = mainColor;
        }else{
            week.textColor = [UIColor colorWithHexString:@"#666666"];
        }
        week.text = weekArray[i];
        week.textAlignment = NSTextAlignmentCenter;
        week.font = [UIFont systemFontOfSize:12];
        week.backgroundColor = [UIColor colorWithHexString:@"#eeeeee"];
        [self addSubview:week];
    }
    
    
    _calendar = [[FSCalendar alloc] initWithFrame:CGRectMake(0, 116, Screen_Width, self.frame.size.height-116)];
    _calendar.backgroundColor = [UIColor whiteColor];
    _calendar.dataSource = self;
    _calendar.delegate = self;
    _calendar.pagingEnabled = NO;
    _calendar.allowsMultipleSelection = YES;
    _calendar.rowHeight = 50;
    _calendar.placeholderType = FSCalendarPlaceholderTypeNone;
    [self addSubview:_calendar];
    _calendar.appearance.titleDefaultColor = [UIColor colorWithHexString:@"#333333"];
    _calendar.appearance.headerTitleColor = [UIColor colorWithHexString:@"#333333"];
    _calendar.appearance.titleFont = [UIFont systemFontOfSize:15];
    _calendar.appearance.headerTitleFont = [UIFont systemFontOfSize:14];
    _calendar.weekdayHeight = 0;
    _calendar.appearance.headerDateFormat = @"yyyy年MM月";
    _calendar.swipeToChooseGesture.enabled = YES;
    _calendar.today = nil; // Hide the today circle
    [_calendar registerClass:[RangePickerCell class] forCellReuseIdentifier:@"cell"];
    
    self.gregorian = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    self.dateFormatter = [[NSDateFormatter alloc] init];
    self.dateFormatter.dateFormat = @"yyyy-MM-dd";
    
    // Uncomment this to perform an 'initial-week-scope'
    // self.calendar.scope = FSCalendarScopeWeek;
    
    // For UITest
    self.calendar.accessibilityIdentifier = @"calendar";
}

#pragma mark - FSCalendarDataSource

- (NSDate *)minimumDateForCalendar:(FSCalendar *)calendar
{
    return [self.dateFormatter dateFromString:@"2006-07-08"];
}

- (NSDate *)maximumDateForCalendar:(FSCalendar *)calendar
{
    return [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:10 toDate:[NSDate date] options:0];
}

- (NSString *)calendar:(FSCalendar *)calendar titleForDate:(NSDate *)date
{
    if ([self.gregorian isDateInToday:date]) {
        return @"今";
    }
    return nil;
}
- (UIColor *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance titleDefaultColorForDate:(NSDate *)date  {
    if ([self.gregorian isDateInToday:date]) {
        return mainColor;
    }
    return [UIColor colorWithHexString:@"#333333"];
}

- (NSString *)calendar:(FSCalendar *)calendar subtitleForDate:(NSDate *)date {
    if (self.startDate && [self.gregorian isDate:self.startDate inSameDayAsDate:date]) {
        return @"开始";
    }else if (self.endDate && [self.gregorian isDate:self.endDate inSameDayAsDate:date]) {
        return @"结束";
    }
    return @"";
}

- (CGPoint)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance subtitleOffsetForDate:(NSDate *)date {
    return CGPointMake(0, 15);
}

- (FSCalendarCell *)calendar:(FSCalendar *)calendar cellForDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition
{
    RangePickerCell *cell = [calendar dequeueReusableCellWithIdentifier:@"cell" forDate:date atMonthPosition:monthPosition];
    return cell;
}

- (void)calendar:(FSCalendar *)calendar willDisplayCell:(FSCalendarCell *)cell forDate:(NSDate *)date atMonthPosition: (FSCalendarMonthPosition)monthPosition
{
    [self configureCell:cell forDate:date atMonthPosition:monthPosition];
}

#pragma mark - FSCalendarDelegate

- (BOOL)calendar:(FSCalendar *)calendar shouldSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition
{
    return monthPosition == FSCalendarMonthPositionCurrent;
}

- (BOOL)calendar:(FSCalendar *)calendar shouldDeselectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition
{
    return monthPosition == FSCalendarMonthPositionCurrent;
}

- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition
{
    if (_isStartDate) {
        self.startDate = date;
        _isStartDate = NO;
        if (self.endDate == nil) {
            _blueLine.frame = CGRectMake(Screen_Width/2.0, 86, Screen_Width/2.0, 4);
            self.startTitleLabel.frame = CGRectMake(0, 45, Screen_Width/2.0, 22);
            self.startTitleLabel.font = [UIFont systemFontOfSize:12];
            self.startDateLabel.text = [self.dateFormatter stringFromDate:self.startDate];
            [self addSubview:self.startDateLabel];
            [self openCalendar];
        }else{
            NSComparisonResult result = [self.startDate compare:self.endDate];
            switch (result) {
                    //结束时间比开始时间大
                case NSOrderedAscending:
                    self.SelectDateBlock(self.startDate, self.endDate);
                    break;
                    //结束时间比开始时间小
                case NSOrderedDescending:
                    self.SelectDateBlock(self.endDate, self.startDate);
                    break;
                    //两者时间相等
                default:
                    self.SelectDateBlock(self.startDate, self.endDate);
                    break;
            }
            [self cancel];
        }
        
    }else{
        self.endDate = date;
        _isStartDate = YES;
        if (self.startDate == nil) {
            _blueLine.frame = CGRectMake(0, 86, Screen_Width/2.0, 4);
            self.endTitleLabel.frame = CGRectMake(Screen_Width/2.0, 45, Screen_Width/2.0, 22);
            self.endTitleLabel.font = [UIFont systemFontOfSize:12];
            self.endDateLabel.text = [self.dateFormatter stringFromDate:self.endDate];
            [self addSubview:self.endDateLabel];
            [self openCalendar];
        }else{
            NSComparisonResult result = [self.startDate compare:self.endDate];
            switch (result) {
                    //结束时间比开始时间大
                case NSOrderedAscending:
                    self.SelectDateBlock(self.startDate, self.endDate);
                    break;
                    //结束时间比开始时间小
                case NSOrderedDescending:
                    self.SelectDateBlock(self.endDate, self.startDate);
                    break;
                    //两者时间相等
                default:
                    self.SelectDateBlock(self.startDate, self.endDate);
                    break;
            }
            [self cancel];
        }
    }

    [self.calendar reloadData];
    
//    if (calendar.swipeToChooseGesture.state == UIGestureRecognizerStateChanged) {
//        // If the selection is caused by swipe gestures
//        if (!self.startDate) {
//            self.startDate = date;
//        } else {
//            if (self.endDate) {
//                [calendar deselectDate:self.endDate];
//            }
//            self.endDate = date;
//        }
//    } else {
//        if (self.endDate) {
//            [calendar deselectDate:self.startDate];
//            [calendar deselectDate:self.endDate];
//            self.startDate = date;
//            self.endDate = nil;
//        } else if (!self.startDate) {
//            self.startDate = date;
//        } else {
//            self.endDate = date;
//        }
//    }
    
    [self configureVisibleCells];
}

- (void)calendar:(FSCalendar *)calendar didDeselectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition
{
    NSLog(@"did deselect date %@",[self.dateFormatter stringFromDate:date]);
    if (_isStartDate) {
        self.startDate = date;
        _isStartDate = NO;
        if (self.endDate == nil) {
            _blueLine.frame = CGRectMake(Screen_Width/2.0, 85, Screen_Width/2.0, 4);
            self.startTitleLabel.frame = CGRectMake(0, 45, Screen_Width/2.0, 22);
            self.startTitleLabel.font = [UIFont systemFontOfSize:12];
            self.startDateLabel.text = [self.dateFormatter stringFromDate:self.startDate];
            [self addSubview:self.startDateLabel];
            [self openCalendar];
        }else{
            NSComparisonResult result = [self.startDate compare:self.endDate];
            switch (result) {
                    //结束时间比开始时间大
                case NSOrderedAscending:
                    self.SelectDateBlock(self.startDate, self.endDate);
                    break;
                    //结束时间比开始时间小
                case NSOrderedDescending:
                    self.SelectDateBlock(self.endDate, self.startDate);
                    break;
                    //两者时间相等
                default:
                    self.SelectDateBlock(self.startDate, self.endDate);
                    break;
            }
            [self cancel];
        }
        
    }else{
        self.endDate = date;
        _isStartDate = YES;
        if (self.startDate == nil) {
            _blueLine.frame = CGRectMake(0, 85, Screen_Width/2.0, 4);
            self.endTitleLabel.frame = CGRectMake(Screen_Width/2.0, 45, Screen_Width/2.0, 22);
            self.endTitleLabel.font = [UIFont systemFontOfSize:12];
            self.endDateLabel.text = [self.dateFormatter stringFromDate:self.endDate];
            [self addSubview:self.endDateLabel];
            [self openCalendar];
        }else{
            NSComparisonResult result = [self.startDate compare:self.endDate];
            switch (result) {
                    //结束时间比开始时间大
                case NSOrderedAscending:
                    self.SelectDateBlock(self.startDate, self.endDate);
                    break;
                    //结束时间比开始时间小
                case NSOrderedDescending:
                    self.SelectDateBlock(self.endDate, self.startDate);
                    break;
                    //两者时间相等
                default:
                    self.SelectDateBlock(self.startDate, self.endDate);
                    break;
            }
            [self cancel];
        }
    }
    [self configureVisibleCells];
}

- (NSArray<UIColor *> *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance eventDefaultColorsForDate:(NSDate *)date
{
    if ([self.gregorian isDateInToday:date]) {
        return @[mainColor];
    }
    return @[appearance.eventDefaultColor];
}

#pragma mark - Private methods

- (void)configureVisibleCells
{
    [self.calendar.visibleCells enumerateObjectsUsingBlock:^(__kindof FSCalendarCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDate *date = [self.calendar dateForCell:obj];
        FSCalendarMonthPosition position = [self.calendar monthPositionForCell:obj];
        [self configureCell:obj forDate:date atMonthPosition:position];
    }];
}

- (void)configureCell:(__kindof FSCalendarCell *)cell forDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)position
{
    RangePickerCell *rangeCell = cell;
    if (position != FSCalendarMonthPositionCurrent) {
        rangeCell.middleLayer.hidden = YES;
        rangeCell.selectionLayer.hidden = YES;
        return;
    }
    
    if (self.startDate && self.endDate) {
        // The date is in the middle of the range
        BOOL isMiddle = [date compare:self.startDate] != [date compare:self.endDate];
        rangeCell.middleLayer.hidden = !isMiddle;
    } else {
        rangeCell.middleLayer.hidden = YES;
    }
    BOOL isSelected = NO;
    isSelected |= self.startDate && [self.gregorian isDate:date inSameDayAsDate:self.startDate];
    isSelected |= self.endDate && [self.gregorian isDate:date inSameDayAsDate:self.endDate];
    rangeCell.selectionLayer.hidden = !isSelected;
}

//取消按钮操作
- (void)cancel {
    self.frame = CGRectMake(0, 116, Screen_Width, Screen_Height-116);
    [UIView animateWithDuration:0.25 animations:^{
        self.frame = CGRectMake(0, Screen_Height, Screen_Width, Screen_Height-116);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        [self.backgroundWindow resignKeyWindow];
        self.backgroundWindow.backgroundColor = [UIColor clearColor];
        self.backgroundWindow.hidden = YES;
    }];

}
//打开日历
- (void)openCalendar {
    [self.backgroundWindow addSubview:self];
    self.backgroundWindow.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.8];
    [self.backgroundWindow makeKeyAndVisible];
    self.frame = CGRectMake(0, Screen_Height, Screen_Width, Screen_Height-116);
    [UIView animateWithDuration:0.25 animations:^{
        self.frame = CGRectMake(0, 116, Screen_Width, Screen_Height-116);
    }];
}


@end
